package com.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.reggie.utils.BaseContext;
import com.reggie.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        log.info("拦截到请求：{}", request.getRequestURI());

        //1.获取本次请求URI
        String requestURI = request.getRequestURI();
        //定义不需要处理的URI请求路径
        String[] employeeUrls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/common/**"
        };
        String[] userUrls = new String[]{
                "/front/**",
                "/user/sendMsg", //移动端发送短信
                "/user/login"   //移动端登录
        };
        //2.判断本次请求是否需要处理
        boolean checkEmployee = check(employeeUrls, requestURI);
        boolean checkUser = check(userUrls, requestURI);
        //3.如果不需要处理，直接放行
        if (checkEmployee || checkUser) {
//            log.info("本次请求{}不需要处理", requestURI);
            //放行资源
            filterChain.doFilter(request,response);
            return;
        }
        //4-1.判断后端登陆状态，如果已登陆，直接放行
        Long employee = (Long) request.getSession().getAttribute("employee");
        if (employee != null) {
//            log.info("用户已登录，用户id为：{}",employee);
            //登录用户id值放入线程中
            BaseContext.setCurrent(employee);
            //放行资源
            filterChain.doFilter(request,response);
            return;
        }

        //4-2.判断手机端登陆状态，如果已登陆，直接放行
        Long user = (Long) request.getSession().getAttribute("user");
        if (user != null) {
//            log.info("用户已登录，用户id为：{}",user);
            //登录用户id值放入线程中
            BaseContext.setCurrent(user);
            //放行资源
            filterChain.doFilter(request,response);
            return;
        }

        log.info("未登录，禁止访问~~");
        //5.如果未登录则返回未登录结果，通过输出流响应给前端数据
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }

    /**
     * 路径匹配，检查本次请求是否需要处理
     * @param urls
     * @param requestURI
     * @return
     */
    private boolean check(String[] urls,String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }

}
